//
//  WKWebViewController.m
//  WebJS
//
//  Created by liuxiang on 2017/12/6.
//  Copyright © 2017年 liuxiang. All rights reserved.
//

#import "WKWebViewController.h"
#import <WebKit/WebKit.h>

@interface WKWebViewController () <WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;


@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
    NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"1" withExtension:@"html"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:htmlURL];
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    [self.webView loadRequest:request];
    
//    NSString *source = @"function oc_changeValue(){alert('changege value');document.getElementById(\"demo2\").innerHTML = \"这是使用webkit更改之后的数据\";return \"change success\";}";
    NSString *source = @"document.getElementById(\"demo2\").innerHTML = \"这是使用webkit更改之后的数据\";";
//  注入自己写的js
/*
 > * injectionTime: 注入时间
 > > 1. WKUserScriptInjectionTimeAtDocumentStart: 开始加载是注入
 > > 2. WKUserScriptInjectionTimeAtDocumentEnd: 加载完成时注入
 */
    WKUserScript *message = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:message];
    
    // 根据name添加js对webkit的回调 <window.webkit.messageHandlers.<name>.postMessage(<body>);>
    [config.userContentController addScriptMessageHandler:self name:@"oc"];
}

#pragma mark - WKNavigationDelegate
- (void) webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *url = navigationAction.request.URL.absoluteString;
    //    com.taylor.custom:
    if ([url hasPrefix:@"com.taylor.custom://"]) {
        //自定义的URL拦截，执行特殊操作
        // 获取参数列表
        NSArray *array = [url componentsSeparatedByString:@"//"];
        NSArray *paraArray = [array.lastObject componentsSeparatedByString:@"&"];
        UIViewController *customVC = [[UIViewController alloc] init];
        //        customVC.a = paraArray.firstObject;
        //        customVC.b = paraArray.lastObject;
        customVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:customVC animated:YES];
        // 不允许 跳转
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 加载完成
- (void) webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"didFinishnavgation");
    [webView evaluateJavaScript:@"document.title" completionHandler:^(NSString *_Nullable title, NSError * _Nullable error) {
        self.navigationItem.title = title;
    }];
    // 调用HTML中已有的js方法
    [webView evaluateJavaScript:@"hello(\"hello world\")" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"hello result = %@",result);
    }];
    
  
    // 调用自己添加的js方法
//    [webView evaluateJavaScript:@"oc_changeValue()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        NSLog(@"oc_changeValue result = %@",result);
//    }];
    
}

#pragma mark - WKUIDelegate
//TextInput
- (void) webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    NSLog(@"TextInput prompt = %@, defaulttext = %@",prompt, defaultText);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:frame.request.URL.host message:prompt preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = prompt;
        textField.text = defaultText;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler(alertController.textFields.firstObject.text);
                                                          
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action){
                                                          completionHandler(nil);
                                                          
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}
// Alert
- (void) webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"alert message = %@",message);
    // js 里面的alert实现，如果不实现，网页的alert函数无效
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:frame.request.URL.host message:message
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler();
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}
// Confirm
- (void) webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    NSLog(@"Confirm message = %@",message);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:frame.request.URL.host
                                                                             message:message
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler(YES);
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action){
                                                          completionHandler(NO);
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
    
}


#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // 注册的脚本回调
    NSLog(@"html 发送给 webkit的数据 --> <%@> 名称 ---> <%@>",message.body,message.name);
}

#pragma mark - dealloc
- (void) dealloc {
    [_webView.configuration.userContentController removeAllUserScripts];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"oc"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
